<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-8-9
 * Time: 下午 11:02
 */
define('TEMPLATE_ROOT', '/view/template/');

class Author
{
    private $config;

    /*初始化*/
    function __construct()
    {
        $config = require getAbsolutePath(__DIR__, '../config/config.php');
        $this->config = $config;
    }

    /*view:渲染函数*/
    protected function render($template, array $var = array())
    {
        extract($var);   // 抽取数组中的变量
        ob_end_clean(); //关闭顶层的输出缓冲区内容
        ob_start();     // 开始一个新的缓冲区
        require TEMPLATE_ROOT . $template . '.html';  //加载视图view
        $content = ob_get_contents();             // 获得缓冲区的内容
        ob_end_clean();           // 关闭缓冲区

        //ob_end_flush();      // 这个是直接输出缓冲区的内容了，不用再次缓存起来。
        ob_start();            //开始新的缓冲区，给后面的程序用
        return $content;       // 返回文本，此处也可以字节echo出来，并结束代码。
    }

    /*view:验证中心逻辑处理*/
    public function fetchAuthor($result, $param)
    {
        if ($result) {
            /*登录信息下发*/
            $config = $this->config;
            foreach ($config['apps'] as $appName => $appLoginURL) {
                /*登录信息下发到所有应用*/
                $url = $appLoginURL . "&param=" . json_encode($result);
                header("Refresh:0;url=" . $url);
            }
            //返回请求的来源
            header("refresh:0;url=" . $config['apps'][$param]);
            //echo $this->render('login_ok', $result);
        } else {
            $this->fetchLogin($result, $param);
        }
    }

    /*view:验证登录页*/
    public function fetchLogin($result, $param = null)
    {
        if (isset($_SESSION['username']) && isset($_SESSION['password'])) {
            /*已经登录的直接将登录信息下发*/
            $data = array('username' => $_SESSION['username'], 'password' => $_SESSION['password']);
            $this->fetchAuthor($data, $param);
        } else {
            /*未登录：将引导到登录界面*/
            if (gettype($result) === 'array') {
                echo $this->render('login', $param);
            } else {
                $res = array(
                    'app' => $result
                );
                echo $this->render('login', $res);
            }
        }
    }

    /*view:验证登录页*/
    public function fetchTip($tip)
    {
        echo $tip . '请求';
    }

    /*view:退出登录页*/
    public function fetchLogOut($param)
    {
        session_destroy();
        $config = $this->config;
        foreach ($config['app_logout'] as $appName => $site) {
            header('refresh:0;url=' . $site . "&param=" . $appName);
        }
        header('refresh:0;url=' . $config['apps'][$param]);
    }
}